package com.guqin.interview.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guqin.interview.mapper.QuestionFavoriteMapper;
import com.guqin.interview.model.entity.QuestionFavorite;
import com.guqin.interview.service.QuestionFavoriteService;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 题目收藏服务实现
 */
@Service
public class QuestionFavoriteServiceImpl extends ServiceImpl<QuestionFavoriteMapper, QuestionFavorite> implements QuestionFavoriteService {

    @Override
    public boolean favoriteQuestion(Long userId, Long questionId) {
        if (userId == null || questionId == null) {
            return false;
        }
        // 检查是否已经收藏
        if (isQuestionFavorited(userId, questionId)) {
            return true;
        }
        // 创建收藏记录
        QuestionFavorite favorite = new QuestionFavorite();
        favorite.setUserId(userId);
        favorite.setQuestionId(questionId);
        return this.save(favorite);
    }

    @Override
    public boolean unfavoriteQuestion(Long userId, Long questionId) {
        if (userId == null || questionId == null) {
            return false;
        }
        QueryWrapper<QuestionFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .eq("questionId", questionId);
        return this.remove(queryWrapper);
    }

    @Override
    public List<Long> getUserFavoriteQuestionIds(Long userId) {
        if (userId == null) {
            return List.of();
        }
        QueryWrapper<QuestionFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .select("questionId");
        return this.list(queryWrapper).stream()
                .map(QuestionFavorite::getQuestionId)
                .collect(Collectors.toList());
    }

    @Override
    public boolean isQuestionFavorited(Long userId, Long questionId) {
        if (userId == null || questionId == null) {
            return false;
        }
        QueryWrapper<QuestionFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId)
                .eq("questionId", questionId);
        return this.count(queryWrapper) > 0;
    }
} 